ZigZag Conversion(“Z”形转换)

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this:
(字符串”PAYPALISHIRING”以给定的行数写成如下Z形模式)
(you may want to display this pattern in a fixed font for better legibility)

P    A    H   N
A P L S  I  I G
Y     I     R

And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:
(编程实现将字符串以给定行数进行该转换)
string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

1.个人分析
题意是将给定的字符串根据行数先转换为示例所展示的Z形结构,最后将其逐行读取读取构成新的字符串并返回。这里主要就是解决如何将字符串正确的转换,可以使用一个字符串数组来保存转换的结果,将字符串逐列保存到数组中。

2.个人解法

string convert(string s, int numRows)
{
    vector<string> strVec(numRows);
    int n = s.length(), i = 0;
    while (i < n) {
        for (int j = 0; j < numRows && i < n; ++j)
            strVec[j].push_back(s[i++]);
        for (int j = numRows - 2; j >= 1 && i < n; --j)
            strVec[j].push_back(s[i++]);
    }

    string res;
    vector<string>::iterator it;
    for (it=strVec.begin(); it != strVec.end(); ++it) 
        res += *it;

    return res;
}

该解法的时间复杂度为O(n),空间复杂度为O(n)。

3.参考解法

string convert(string s, int numRows)
{
    if(numRows <= 1) return s;
    string result = "";
    int cycle = 2 * numRows - 2;
    for(int i = 0; i < numRows; ++i)
    {
        for(int j = i; j < s.length(); j = j + cycle){
            result = result + s[j];
            int secondJ = (j - i) + cycle - i;
            if(i != 0 && i != numRows-1 && secondJ < s.length())
                result = result + s[secondJ];
        }
    }
    return result;
}

该解法的时间复杂度为O(n),空间复杂度为O(1)。

4.总结
起初对Z形字符串的定义还不是很理解,也就看不出这种字符串的排列规律。这里可以从两方面去看排列规律,未完全填满的中间列(可以理解为斜对角)所包含元素的个数为numRows-2;另外也可以将每一列和斜对角的元素作为一个周期,除了第一行和最后一行,每个周期的每行都含有两个元素。

n=numRows
Δ=2n-2    1                           2n-1                         4n-3
Δ=        2                     2n-2  2n                    4n-4   4n-2
Δ=        3               2n-3        2n+1              4n-5       .
Δ=        .           .               .               .            .
Δ=        .       n+2                 .           3n               .
Δ=        n-1 n+1                     3n-3    3n-1                 5n-5
Δ=2n-2    n                           3n-2                         5n-4

PS:

  • 题目的中文翻译是本人所作,如有偏差敬请指正。
  • 其中的“个人分析”和“个人解法”均是本人最初的想法和做法,不一定是对的,只是作为一个对照和记录。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值